package com.itany.corejava.code13_jdbc;

import javax.xml.crypto.Data;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @author MissChen
 * @date 2024年03月22日 9:01
 */
public class Test05_分页查询 {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.print("请输入查询第几页的数据");
        int pageNo=sc.nextInt();
        System.out.print("请输入每页显示多少条数据");
        int pageSize=sc.nextInt();
        try {
            List<User> users=selectPage(pageNo,pageSize);
            for(User user:users){
                System.out.println(user);
            }
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
    }
    public static List<User> selectPage(Integer pageNo,Integer pageSize) throws DataAccessException {
        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        List<User> users=new ArrayList<>();
        try {
            conn=JDBCUtil.getConnection();
            String sql=new StringBuffer(" select id,username,password,phone,address ")
                    .append(" from t_user ")
                    .append(" limit ?,? ")
                    .toString();
            ps=conn.prepareStatement(sql);
            ps.setInt(1,(pageNo-1)*pageSize);
            ps.setInt(2,pageSize);
            rs=ps.executeQuery();
            while(rs.next()){
                User user=new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                users.add(user);
            }
            return users;
        } catch (DataAccessException e) {
           throw e;
        } catch (SQLException e) {
            throw new DataAccessException("数据库访问异常");
        }
    }
}
